<<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <!--<el-form-item>-->
          <!--<el-input v-model="filters.name" placeholder="任务名称"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item>-->
          <!--<el-button type="primary" v-on:click="getSpiders">查询</el-button>-->
        <!--</el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSpiders">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="spiders" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column fixed type="selection" width="55">
      </el-table-column>
      <el-table-column label="任务名称" prop="name" width="200">
      </el-table-column>
      <el-table-column prop="type_spider" label="爬虫类型" width="120">
      </el-table-column>
      <!--<el-table-column prop="proxy" label="是否使用代理">-->
      <!--</el-table-column>-->
      <el-table-column prop="type_template" label="模版类型">
      </el-table-column>
      <el-table-column prop="type_business" label="业务类型">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template slot-scope="scope">
          <el-button-group>
          <!--<el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
          <el-button size="small" type="success" @click="handleAction(scope.$index, scope.row)">执行任务</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <!--<el-button size="small" type="info" @click="showEchart(scope.$index, scope.row)">显示图表</el-button>-->
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除({{this.sels.length}})</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
      </el-pagination>
    </el-col>

  </section>
</template>

<style scoped>
  .button-list {
  margin-bottom: 10px;
  }
  .el-button {
    padding: 8px 10px;
  }
  form {
    height: 40px;
  }
</style>

<script>
  import { gainTasks, postSpider, postTaskList, deleteAny, postHouseSource, timeFormat } from '../apis/api'
  export default {
    data () {
      return {
        filters: {
          name: ''
        },
        spiders: [],
        total: 0,
        editFormVisible: false, // 编辑界面是否显示
        editLoading: false,
        listLoading: false,
        tableData: [],
        sels: [],
        jsondata: '',
        // endpointDB: this.$store.state.endpointDB,
        endpointSP: this.$store.state.endpointSP,
        path: this.$store.state.path,
        page: 1,
        priceData: []
      }
    },
    methods: {
      getSpiders () {
        let _this = this
        this.listLoading = true
//        getUserListPage(para) 过滤也要用到
        gainTasks(_this.page).then(res => {
          _this.total = res.data.count
          for (let i in res.data.results) {
            res.data.results[i].createTime = timeFormat(res.data.results[i].createTime)
          }
          _this.spiders = res.data.results
          _this.listLoading = false
        }, res => {
          _this.$message({
            message: '出错了，请联系管理员',
            type: 'error'
          })
        })
      },
      // 性别显示转换
      formatSex: function (row, column) {
        return row.sex === 1 ? '男' : row.sex === 0 ? '女' : '未知'
      },
      handleCurrentChange (val) {
        this.page = val
        this.getSpiders()
      },
      // 执行任务
      handleAction: function (index, row) {
        let _this = this
        _this.$confirm('确认执行该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          _this.listLoading = true
          // NProgress.start();
//          let para = { id: row.id }
          // 删除接口
          // 判断调用的爬虫
          let downfile = this.path + row.name + '.csv'
          let myData = {}
          switch (row.type_business) {
            case '单网页采集':
//              let tmp = JSON.stringify(['http://news.baidu.com'])
//              alert(row.website)
              myData = {
                project: 'nlproject',
                spider: 'single',
                start_urls: row.website,
                xpaths: row.xpath,
                setting: 'FEED_URI=' + downfile
              }
              break
            case '表格采集':
              myData = {
                project: 'nlproject',
                spider: 'table',
                start_urls: row.website,
                trXpath: row.myTr,
                tdXpath: row.myTd,
                setting: 'FEED_URI=' + downfile
              }
              break
            case '列表及详情采集':
              myData = {
                project: 'nlproject',
                spider: 'list',
                xpaths: row.xpath,
                frontUrl: row.frontUrl,
                backUrl: row.backUrl,
                trXpath: row.myTr,
                startNum: row.startNum,
                endNum: row.endNum,
                increase: row.myIncrease,
                setting: 'FEED_URI=' + downfile
              }
              break
            case 'URL列表采集':
              myData = {
                project: 'nlproject',
                spider: 'url',
                xpaths: row.xpath,
                start_urls: row.website,
                setting: 'FEED_URI=' + downfile
              }
              break
            case '标签寻址':
              myData = {
                project: 'nlproject',
                spider: 'keySpider',
                start_urls: row.website,
                xpaths: row.xpath,
                setting: 'FEED_URI=' + downfile,
                keys: row.keyword
              }
              break
            case '指定寻址':
              myData = {
                project: 'nlproject',
                spider: 'keySpider',
                website: row.website,
                xpath: row.xpath,
                startNum: row.startNum,
                endNum: row.endNum,
                xlsheadtitle: row.myTd,
                name: row.name
              }
              break
          }
          if (row.type_business === '指定寻址') {
            postHouseSource(myData).then(res => {
              let downfile = 'http://www.nlelearn.com/spider/download/' + row.name
              _this.listLoading = false
              let taskListData = {jid: row.url.split('/')[row.url.split('/').length - 2], task: row.url, name: row.name, type_spider: row.type_spider, type_template: row.type_template, type_business: row.type_business, downloadURL: downfile}
              taskListData = JSON.stringify(taskListData)
              postTaskList(taskListData).then(res => {  // XXX: 插入任务记录
              }).catch(res => {
                alert(res)
              })
              _this.$message({
                message: '执行成功，请稍后查看',
                type: 'success'
              })
              _this.getSpiders()
            }, res => {
              alert(res)
            })
          } else {
            postSpider(myData).then(res => {  // TODO: 目前下载就按名字了
              _this.listLoading = false
              // NProgress.done();
              let jobId = res.data.jobid
              let taskListData = {jid: jobId, task: row.url, name: row.name, type_spider: row.type_spider, type_template: row.type_template, type_business: row.type_business, downloadURL: downfile}
              postTaskList(taskListData).then(res => {  // XXX: 插入任务记录
              }).catch(res => {
                console.log(res)
              })  // XXX: 添加下载记录
              _this.$message({
                message: '执行成功，请稍后查看',
                type: 'success'
              })
              _this.getSpiders()
            }).catch(res => {
              _this.$message({
                message: '执行失败，请重试',
                type: 'error'
              })
              _this.getSpiders()
            })
          }
        }).catch(() => {

        })
      },
      // 执行记录
      handleRecord: function (index, row) {  // TODO: 记录列表
      },
      // 显示编辑界面 TODO: 跳转到爬虫form界面 使用store传值
      handleEdit: function (index, row) {
        let myKey = ''
        switch (row.type_business) {
          case '单网页采集':
            myKey = '1-6-1'
            break
          case '表格采集':
            myKey = '1-6-2'
            break
          case '列表及详情采集':
            myKey = '1-6-3'
            break
          case 'URL列表采集':
            myKey = '1-6-4'
            break
          case '标签寻址':
            myKey = '1-7'
            break
        }
        this.$store.dispatch('addTab', {'tab': {
          title: row.type_business,
          name: myKey,
          components: myKey,
          closed: true
        },
          'activeName': myKey})
      },
      // 显示新增界面
      handleAdd: function () {
        this.$store.dispatch('addTab', {'tab': {
          title: '添加爬虫',
          name: '1-5',
          components: '1-5',
          closed: true
        },
          'activeName': '1-5'})
      },
      handleDelete: function (index, row) {
        let _this = this
        _this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          _this.listLoading = true
          // NProgress.start();
//          let para = { ids: ids }
          // 接口
          deleteAny(row.url).then(res => {  // TODO: 修复 目前只能删一个
            _this.listLoading = false
            _this.$message({
              message: '删除成功',
              type: 'success'
            })
            _this.getSpiders()
          }).catch(res => {
          })
        }).catch(() => {
        })
      },
      selsChange: function (sels) {
        this.sels = sels
      },
      // 批量删除
      batchRemove: function () {
        let _this = this
//        let urls = _this.sels.map(item => item.url)
        _this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          _this.listLoading = true
          // NProgress.start();
//          let para = { ids: ids }
          // 接口
          _this.sels.forEach(function (item) {
            deleteAny(item.url).then(res => {  // TODO: 修复 目前只能删一个
              _this.listLoading = false
              _this.getSpiders()
            }).catch(res => {
              console.log(res)
            })
            _this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        }).catch(() => {
        })
      }
      // showEchart (index, row) {
      //   this.$store.dispatch('addTab', {'tab': {
      //     title: row.name,
      //     name: '4-1',
      //     components: '4-1',
      //     closed: true
      //   },
      //     'activeName': '4-1'})
      // }
    },
    mounted () {
      this.getSpiders()
    }
  }
</script>

